#ifndef MEMOMODEL_H
#define MEMOMODEL_H

#include <QObject>
#include <QAbstractListModel>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
#include <QDebug>

// 备忘录项数据结构
struct MemoItem {
    int id;
    QString title;
    QString content;
    QDateTime createdAt;
    QDateTime updatedAt;
    
    MemoItem() : id(-1) {}
    MemoItem(int id, const QString &title, const QString &content, 
             const QDateTime &createdAt, const QDateTime &updatedAt)
        : id(id), title(title), content(content), 
          createdAt(createdAt), updatedAt(updatedAt) {}
};

// 备忘录模型类 - 继承自QAbstractListModel，可在QML中直接使用
class MemoModel : public QAbstractListModel
{
    Q_OBJECT
    
    // QML属性
    Q_PROPERTY(int count READ rowCount NOTIFY countChanged)
    
public:
    // 角色枚举，用于QML中访问数据
    enum MemoRoles {
        IdRole = Qt::UserRole + 1,
        TitleRole,
        ContentRole,
        CreatedAtRole,
        UpdatedAtRole
    };
    
    explicit MemoModel(QObject *parent = nullptr);
    ~MemoModel();
    
    // QAbstractListModel接口实现
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    QHash<int, QByteArray> roleNames() const override;
    
    // 数据库操作
    Q_INVOKABLE bool addMemo(const QString &title, const QString &content);
    Q_INVOKABLE bool updateMemo(int id, const QString &title, const QString &content);
    Q_INVOKABLE bool deleteMemo(int id);
    Q_INVOKABLE QVariantMap getMemo(int index) const;
    
    // 初始化数据库
    bool initDatabase();
    
signals:
    void countChanged();
    void errorOccurred(const QString &error);
    
private:
    QList<MemoItem> m_memos;
    QSqlDatabase m_database;
    
    // 从数据库加载所有备忘录
    void loadMemos();
    
    // 数据库连接
    bool connectDatabase();
};

#endif // MEMOMODEL_H

